from channels.generic.websocket import WebsocketConsumer
from channels.exceptions import StopConsumer


import json
import random
import requests
from twisted_iocpsupport.iocpsupport import send

client_id = 'HQ24GgKkrXqxLbTPmlSkp1H6'
client_secret = '5RHkMKRCw9Qx159wZwYqLOnka6bnpeD7'


def unit_chat(chat_input, user_id=8888):
    chat_reply = '谢谢,客服不在，请稍等'
    url = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=%s&client_secret=%s" % (
    client_id, client_secret)

    ret = requests.get(url)

    access_token = eval(ret.text)['access_token']

    post_data = {
        "log_id": str(random.random()),
        "request": {
            "query": chat_input,
            "user_id": user_id
        },
        "session_id": "",
        "service_id": "S103410",
        "version": "2.0"
    }
    # unit_chatbot_url = "https://aip.baidubce.com/rpc/2.0/unit/service/chat?access_token=" + access_token
    unit_chatbot_url = "https://aip.baidubce.com/rpc/2.0/unit/service/chat?access_token=" + access_token

    res = requests.post(unit_chatbot_url, json=post_data)
    unit_chat_obj = json.loads(res.content)
    # result-response_list-schema-intent_confidence-action_list-say
    if unit_chat_obj['error_code'] != 0:
        return chat_reply

    unit_chat_result = unit_chat_obj['result']
    unit_chat_response_list = unit_chat_result['response_list']
    unit_chat_response_obj = random.choice([unit_chat_response for unit_chat_response in unit_chat_response_list if
                                            unit_chat_response['schema']['intent_confidence'] > 0.0])
    unit_chat_action = unit_chat_response_obj['action_list']
    unit_chat_action_obj = random.choice(unit_chat_action)
    unit_chat_say = unit_chat_action_obj['say']

    return unit_chat_say





class ChatConsumer(WebsocketConsumer):  # 继承WebsocketConsumer
   def websocket_connect(self, message):
       print("有人进行连接了。。。。")
       # 有客户端向后端发送 WebSocket 连接的请求时，自动触发(握手)
       chat_input = message.get('msg')
    # 调用unit_chat函数生成回复消息
       result_say = unit_chat(chat_input)
        # 将生成的回复消息添加到原消息中
       message['msg'] = result_say
        # 打印消息内容
       print(message)
        # 广播消息给所有客户端
       # send(message, broadcast=True)
       self.accept(message)

   def websocket_receive(self, message):
       # 浏览器基于 WebSocket 向后端发送数据，自动触发接收消息
       print(message)
       self.send("不要回复不要回复！！！")

   def websocket_disconnect(self, message):
       # 客户端向服务端断开连接时，自动触发
       print("连接断开！！")
       raise StopConsumer()
